<?php

namespace App\Http\Controllers;

use App\Http\Requests\UserRegister;
use App\Http\Requests\UserLogin;
use App\User;
use App\Upload;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function register(){
      return view('auth.register');
    }

    public function registerPost(UserRegister $request){
      $data = ['avatar'=>'/images/default-avatar.jpg','confirm_code'=>str_random(60)];
      $user = User::create(array_merge($request->all(),$data));
      $view = 'auth.register-email';
      $subject = '确认你的邮箱';
      $this->sendTo($user, $subject, $view, $data);
      return redirect('/');
    }

    public function login(){
      return view('auth.login');
    }

    public function loginPost(UserLogin $request){
      $is_remember = boolval($request->get('remember'));
      if(\Auth::attempt([
          'email'=>$request->get('email'),
          'password'=>$request->get('password'),
          'status'=>1,
        ],$is_remember)){
        return redirect('');
      }
      $email = "邮箱密码不匹配";
      return \Redirect::back()->withErrors(['email'=>$email]);
    }

    public function logout(){
      \Auth::logout();
      return redirect('/');
    }

    public function confirmEmail($code){
      $user = User::where('confirm_code',$code)->first();
      if(!$user){
        return redirect('/');
      }

      $user->status = 1;
      $user->confirm_code = str_random(60);
      $user->save();
      return redirect(''); 
    }

    public function avatar(){
      return view('auth.avatar');
    }

    public function avatarPost(Request $request){
        $file = $request->file('avatar');
        $input = array('avatar' => $file);
        $rules = array(
            'avatar' => 'image'
        );
        $validator = \Validator::make($input, $rules);
        if ( $validator->fails() ) {
            return response()->json([
                'success' => false,
                'errors' => $validator->getMessageBag()->toArray()
            ]);
        }
      /*$this->validate($request,[
          'avatar' => 'required',
        ]);*/
      if($request->hasFile('avatar') && $request->file('avatar')->isValid()){
        $avatar = $request->file('avatar')->store(Upload::getUploadFolder());
      }
      $user = User::find(\Auth::user()->id);
      $user->avatar = '/upload/'.$avatar;
      $user->save();
      //return redirect('user/avatar');
      return response()->json(
          [
            'success' => true,
            'avatar' => asset('/upload/'.$avatar),
          ]
      );
    }

    private function sendTo($user, $subject, $view, $data){
      \Mail::send($view,$data,function($message) use ($user,$subject){
        $message->to('woshilieqie@163.com')
                ->subject($subject);
      });
    }
}
